<template>
  <view>
    <view class="product-recommend" :style="Object.assign({}, recommendStyle, { pointerEvents: isEditMode ? 'none' : 'auto' })" @click.stop="handleEditModeClick">
      <view class="recommend-title" :style="titleStyle">商品推荐</view>
      <view class="recommend-grid" :style="gridStyle">
        <view class="product-card" v-for="(item, index) in imgList" :key="item.id || index" @click="toDetail(item)">
          <image
              :src="getFullImgUrl(item.f_thumb)"
              mode="aspectFill"
              style="width: 100%; height: 8.5rem; border-radius: 12px;"
          />
          <view class="shopName" :style="getNameStyle(item)">{{ item.title }}</view>
          <view class="money">
            <image
                src="../../static/images/money.png"
                mode="widthFix"
                style="width: 20px;height: 20px"
            />
            <view class="shopPrice" :style="getPriceStyle(item)"> {{ item.price }}</view>
            <image
                src="../../static/images/shopCar.png"
                mode="widthFix"
                style="width: 20px;height: 20px"
            />
          </view>
        </view>
      </view>
      <view class="loading-tip" v-if="isLoading">
        <text>加载中...</text>
      </view>
      <view class="no-more-tip" v-if="!isLoading && !hasMore">
        <text>没有更多商品了</text>
      </view>
    </view>
    <view style="width: 100%;height: 30px">
    </view>
  </view>
</template>

<script>
import { shopList } from "../../api/newShop/index";

function parseLayout(layout) {
  if (typeof layout === 'string') {
    try {
      return JSON.parse(layout);
    } catch (e) {
      return {};
    }
  }
  return layout || {};
}

export default {
  name: 'ProductRecommend',
  props: {
    isEditMode: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      imgList: [],
      nextPage: null,
      isLoading: false,
      hasMore: true,
      pageSize: 10,
      shopCar:"",
      money:"",
      resLayout: '' // 保存接口返回的layout字符串
    };
  },
  mounted() {
    this.getShopList();
  },
  computed: {
    parsedLayout() {
      try {
        return typeof this.resLayout === 'string' ? JSON.parse(this.resLayout) : (this.resLayout || {});
      } catch (e) {
        return {};
      }
    },
    recommendStyle() {
      // 严格参考 QuickEntry.vue，优先用接口 layout.recommend_goods_bgc
      let bgc = '#fff';
      if (this.parsedLayout && this.parsedLayout.recommend_goods_bgc) {
        bgc = this.parsedLayout.recommend_goods_bgc;
      }
      return {
        marginTop: '10px',
        marginBottom: '16px',
        background: bgc,
        borderRadius: '12px',
        padding: '16px 0 20px 0',
        width: '95%',
        marginLeft: '.6rem',
        transition: 'all 0.3s ease',
      };
    },
    gridStyle() {
      return {
        display: 'grid',
        gridTemplateColumns: '1fr 1fr',
        gap: '12px',
      };
    },
    titleStyle() {
      return {
        fontSize: '16px',
        color: '#222',
        fontWeight: 500,
        marginBottom: '12px',
        marginLeft: '.7rem',
      };
    },
  },
  methods: {
    getNameStyle(item) {
      const style = item.style || {};
      return {
        color: style.textColor || '#172029',
        fontWeight: 700,
        fontSize: style.fontSize ? style.fontSize + 'px' : '15px',
        margin: '4px 0 0 5px',
      };
    },
    getPriceStyle(item) {
      const style = item.style || {};
      return {
        color: style.textColor || '#fc5e02',
        fontWeight: 700,
        fontSize: style.fontSize ? style.fontSize + 'px' : '18px',
        margin: '0 0 0 5px',
      };
    },
    getShopList() {
      if (this.isLoading || !this.hasMore) return;
      this.isLoading = true;
      const params = {};
      if (this.nextPage) {
        params.recommend_next_page = this.nextPage;
      }
      shopList(params).then(res => {
        if (res.code === 200) {
          this.imgList = [...this.imgList, ...res.data.recommend_goods];
          this.nextPage = res.data.recommend_next_page;
          if (res.data.layout) {
            this.resLayout = res.data.layout;
          }
          if (!this.nextPage) {
            this.hasMore = false;
          }
        } else {
          uni.showToast({
            title: res.message || '获取商品列表失败',
            icon: 'none'
          });
        }
      }).catch(err => {
        console.error('获取商品列表失败：', err);
        uni.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      }).finally(() => {
        this.isLoading = false;
      });
    },
    toDetail(item) {
      // 编辑模式下阻止导航
      if (this.isEditMode) {
        return;
      }
      
      if (!item || !item.id) return;
      const isLogin = uni.getStorageSync("isLogin");
      if (!isLogin) {
        uni.navigateTo({
          url: "/pagesAuth/public/login/index"
        });
      } else {
        uni.navigateTo({
          url: `/pagesCommon/detail/index?shop_id=${item.id}&type=newShop`
        });
      }
    },
    getFullImgUrl(thumb) {
      const baseUrl = getApp().globalData.baseUrl;
      return thumb.startsWith("http") ? thumb : baseUrl + thumb;
    },
    handleClick(event) {
      // 检查是否在编辑模式下
      if (this.isEditMode) {
        // 编辑模式下，阻止默认行为
        event.preventDefault();
        event.stopPropagation();
        
        this.$emit('component-click', 'productRecommend', {
          items: this.imgList
        }, event);
      }
      // 非编辑模式下，允许正常的点击行为
    },
    handleEditModeClick(event) {
      if (this.isEditMode) {
        event.preventDefault();
        event.stopPropagation();
      }
    },
    updateConfig(config) {
      if (config && config.items) {
        this.imgList = config.items;
      }
      this.$forceUpdate();
    },
    loadMoreProducts() {
      if (this.isLoading || !this.hasMore) return;
      this.isLoading = true;
      const params = {};
      if (this.nextPage) {
        params.recommend_next_page = this.nextPage;
      }
      shopList(params).then(res => {
        if (res.code === 200) {
          this.imgList = [...this.imgList, ...res.data.recommend_goods];
          this.nextPage = res.data.recommend_next_page;
          if (res.data.layout) {
            this.resLayout = res.data.layout;
          }
          if (!this.nextPage) {
            this.hasMore = false;
          }
        } else {
          uni.showToast({
            title: res.message || '获取商品列表失败',
            icon: 'none'
          });
        }
      }).catch(err => {
        console.error('获取商品列表失败：', err);
        uni.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      }).finally(() => {
        this.isLoading = false;
      });
    }
  },
  onReachBottom() {
    this.loadMoreProducts();
  }
};
</script>

<style scoped>
.product-recommend {
  width: 95%;
  margin-left: .6rem;
  /* 背景色、圆角、padding、margin 由 :style 控制 */
}
.recommend-title {
  font-size: 16px;
  font-weight: 500;
  margin-bottom: 12px;
  margin-left: .7rem;
}
.recommend-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
}
.product-card {
  width: 92%;
  margin-left: .7rem;
  border-radius: 10px;
  height: 14rem;
  /* 其它样式可根据需要补充 */
}
.loading-tip,
.no-more-tip {
  text-align: center;
  padding: 16px;
  color: #999;
  font-size: 14px;
}
.shopName{
  width: 100%;
  color: #172029;
  font-weight: 700;
  font-size: 15px;
  margin: 4px 0 0 5px;
}
.shopPrice{
  width: 100%;
  color: #fc5e02;
  font-weight: 700;
  font-size: 18px;
  margin: 0 0 0 5px;
}
.money{
  margin-top: 10px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
</style>